﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;


/// <summary>
/// 输入事件管理
/// </summary>
public class RInputModuleEvent : MonoBehaviour
{
    public void Start()
    {
        this.InitListeners();
    }
    private void Update()
    {
        DoListenKeyState();
    }



    public static Dictionary<KeyCode, RInputModuleListener> Listeners = new Dictionary<KeyCode, RInputModuleListener>();
    public static void Register(KeyCode keyCode)
    {
        Listeners.TryAdd(keyCode, new RInputModuleListener());
    }
    public static void UnRegister(KeyCode keyCode)
    {
        Listeners.Remove(keyCode);
    }
    public static RInputModuleListener Get(KeyCode keyCode)
    {
        return Listeners[keyCode];
    }


    HashSet<KeyCode> _previousKeyStates = new();


    private void InitListeners()
    {
        foreach (KeyCode keyCode in Enum.GetValues(typeof(KeyCode)))
        {
            if (!Listeners.ContainsKey(keyCode))
            {
                Listeners.Add(keyCode, new RInputModuleListener());
            }
        }
    }
    private void DoListenKeyState()
    {
        HashSet<KeyCode> currentPressedKeys = Enum.GetValues(typeof(KeyCode))
            .Cast<KeyCode>()
            .Where(key => Input.GetKey(key))
            .ToHashSet();


        var changedKeys = new List<KeyEvent>();

        // 检查新增按键
        foreach (var key in currentPressedKeys)
        {
            if (!_previousKeyStates.Contains(key))
            {
                changedKeys.Add(new KeyEvent(key, true));
            }
        }

        // 检查已释按键
        foreach (var key in _previousKeyStates)
        {
            if (!currentPressedKeys.Contains(key))
            {
                changedKeys.Add(new KeyEvent(key, false));
            }
        }

        // 有状态变化时触发事件
        if (changedKeys.Count > 0)
        {
            foreach (var item in changedKeys)
            {
                Get(item.KeyCode).Invoke(item);
            }
        }

        // 更新缓存为当前状态
        _previousKeyStates = currentPressedKeys;
    }
}